from flask import request,Flask
import time
import json
import requests
from threading import Thread
from gevent import pywsgi

# 实例化Flask类
app = Flask(__name__)

# 转储应答接口
@app.route("/", methods=['POST','GET'])
def HelloWorld():
    return "Hello World!"


def dumpCallBack():
    time.sleep(10)
    param_data = {"type": "video.ftp_download", "params": {"source": "ftp://scms:scms@172.19.97.162:21//opt/scms/NAS/2023/06/21/109/109.mp4", "target": {"enablePathStyle": True, "ak": "NISF3K9CZDFC677ANX58", "bucket": "/opt", "host": "http://172.19.97.162:8081", "sk": "A0dnoMN4RWqzrUB9cqrRrhDFtk9zNo9PlvYQuLVj", "enableCephAcl": False, "subTaskResultObject": "dumpTask/2023/5/31/8028-145935.txt", "object": "scms/NAS/2023/06/21/109/109.mp4"}, "mode": "", "resolutionLowerLimit": 225, "durationUpperLimit": 14400, "cachedTaskId": "", "taskId": "488_20230621151940"}}

	# 从文件读取JSON数据
    with open('dumpcallback.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    # print('data:', data)
    data["taskId"] = CorrelateID
    param_data["params"]["taskId"] = jobId
    param_data["params"]["source"] = ftpdir
    movedir = ftpdir.split("opt")
    param_data["params"]["target"]["object"] = movedir[1]
    data["param"] = str(param_data)

    # 将数据写入JSON文件
    with open('dumpcallback.json', 'w', encoding='utf-8') as f:
        json.dump(data, f)

    headers = {'Content-Type': 'application/json;charset=UTF-8'}
    url = "http://172.19.97.161:7002/scms-vcr/audit/dump/feedback/" + jobId
    print('百度转储回调url',url)
    response = requests.post(url, data=json.dumps(data), headers=headers)
    print("转储回调请求状态码：", response.status_code)
    print("转储回调响应结果：", response.text)

# 转储应答接口
@app.route("/v1/remote-process", methods=['POST'])
def dumpRsp():
    global jobId, callback, ftpdir,CorrelateID
    timestamp = int(time.time())
    date_time = time.strftime('%Y%m%d%H%M%S', time.localtime(timestamp))
    CorrelateID = "BaiduAuto_" + date_time

    result ={"workflowId": CorrelateID}

    jobId = request.json.get("jobId").strip() # token
    callback = request.json.get("callback").strip() # 回调地址
    stdin = request.json.get("stdin").strip() # 请求信息
    print("jobId:", jobId)
    print("callback:", callback)



    # 将请求的stdin内容转换成dict格式
    data = json.loads(stdin)
    # print(type(data),data)

    # 提取ftp地址
    paramdata = data["param"]
    ftpdata = json.loads(paramdata)
    # print(type(ftpdata),ftpdata)
    ftpdir = ftpdata["params"]["source"]
    print("ftp地址：", ftpdir)

    thread = Thread(target=dumpCallBack)
    thread.start()
    # 百度转储应答
    print("百度转储应答:", result)
    return result

def contentAuditBack(taskId,source):
    time.sleep(10)
    # 从文件读取JSON数据
    with open('ContentAuditBack.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    # print(data)
    data["taskId"] = taskId
    data["source"] = source
    data["url"] = source
    print('节目时长:',data["duration"])

    # 将数据写入JSON文件
    with open('ContentAuditBack.json', 'w', encoding='utf-8') as f:
        json.dump(data, f)

    headers = {'Content-Type': 'application/json;charset=UTF-8'}
    url = "http://172.19.97.161:7002/scms-vcr/audit/baiduAuditResult"
    print("百度内容审核回调url：", url)
    response = requests.post(url, data=json.dumps(data), headers=headers)
    print("内容审核回调请求状态码：", response.status_code)
    print("内容审核回调响应结果：", response.text)

# 内容审核应答接口
@app.route("/v2/vcr/media", methods=['PUT'])
def AutoTypeOne():
    result = {"userName": "default",
    "taskId": "f82m241234132andy41s8",
    "source": "http://172.19.97.162:8081//opt/scms/NAS/blues/liyifeng-douyin.mp4",
    "url": "",
    "description": "",
    "preset": "default",
    "status": "PROVISIONING",
    "notification": "scms",
    "createTime": "2023-06-02T06:58:58Z",
    "streamId": "","callbackType": "vcr"}


    req_data = request.data.decode('utf-8')  # 获取请求数据
    data = json.loads(req_data)
    print("内容审核请求data：", data)
    result["source"] = data["source"]

    timestamp = int(time.time())
    date_time = time.strftime('%Y%m%d%H%M%S', time.localtime(timestamp))
    CorrelateID = "AutoTypeOne_" + date_time
    result["taskId"] = CorrelateID

    thread = Thread(target=contentAuditBack,kwargs={"taskId":CorrelateID,"source":data["source"]})
    thread.start()
    print("百度内容审核应答:", result)
    return result

# 质量审核回调
def qualityCallBack(taskId,source):
    time.sleep(10)
    # messageBody = {"jobId": "AutoTypeTwo_20230626203942", "pipelineName": "test", "jobStatus": "SUCCESS", "createTime": "2023-06-06T06:58:58Z", "startTime": "2023-06-06T06:58:58Z", "endTime": "2023-06-06T07:05:12Z", "source": {"url": "http://172.16.20.128:8086/transcode/dumpTask/2023/5/31/8028-145935.mp4"}, "needTarget": True, "presetName": "all", "usedTime": 374058, "videoDurationInSeconds": 7200, "notification": "http://172.19.97.161:7002/scms-vcr/audit/baiduVideoDetectResult", "result": {"blurEdge": {"success": True, "defects": [], "interval": 1000}, "blur": {"success": True, "defects": [{"score": 0.53655, "start": 92000, "end": 100000}, {"score": 0.50535, "start": 174000, "end": 178000}, {"score": 0.53787, "start": 182000, "end": 186000}, {"score": 0.54137, "start": 264000, "end": 268000}, {"score": 0.55171, "start": 280000, "end": 284000}, {"score": 0.51041, "start": 378000, "end": 386000}, {"score": 0.53127, "start": 500000, "end": 504000}, {"score": 0.50606, "start": 584000, "end": 586000}], "interval": 2000}, "whiteScreen": {"success": True, "defects": [], "interval": 1000}, "blackScreen": {"success": True, "defects": [], "interval": 1000}, "freeze": {"success": True, "defects": [], "interval": 2000}, "jitter": {"success": True, "defects": [], "interval": 1000}, "mosaic": {"success": True, "defects": [], "interval": 1000}, "noise": {"success": True, "defects": [], "interval": 2000}, "crash": {"success": True, "defects": [{"start": 880000, "end": 883000}, {"start": 928000, "end": 930000}, {"start": 941000, "end": 942000}], "interval": 1000}, "block": {"success": True, "defects": [], "interval": 5000}, "freezeMute": {"success": True, "defects": [], "interval": 1000}, "mixedFrame": {"success": True, "defects": [{"start": 91000, "end": 93000}, {"start": 125000, "end": 130000}, {"start": 596000, "end": 602000}, {"start": 669000, "end": 670000}, {"start": 741000, "end": 744000}], "interval": 1000}, "mute": {"success": True, "defects": [], "interval": 1000}, "volumeLow": {"success": True, "defects": [{"score": 0.00903, "start": 492000, "end": 494000}, {"score": 0.00911, "start": 504000, "end": 506000}, {"score": 0.00846, "start": 590000, "end": 592000}], "interval": 2000}, "volumeHigh": {"success": True, "defects": [], "interval": 200}, "soundIntermittent": {"success": True, "defects": [], "interval": 100}}, "mediaInfo": {"type": "video", "format": "mov,mp4,m4a,3gp,3g2,mj2", "formatLongName": "QuickTime / MOV", "fileSizeInByte": 1295575570, "startTimeInSecond": 0.0, "durationInSecond": 1299.936, "videoInfo": {"codecName": "h264", "widthInPixel": 1920, "heightInPixel": 1080, "dar": "16:9", "bitRateInBps": 7897102, "realBaseFrameRate": 25.0, "avgFrameRate": 25.0}, "audioInfo": {"codecName": "aac", "channels": 1, "sampleRateInHz": 48000, "bitRateInBps": 70017}}}
    # 从文件读取JSON数据
    with open('qualityCallback.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    print('质量审核回调data:', type(data), data)
    messageBody = json.loads(data["messageBody"]) # dict
    # print("messageBody参数:", type(messageBody), messageBody)

    # print("result_data:", type(result_data), result_data)

    messageBody["jobId"] = taskId
    messageBody["source"]["url"] = source

    messageBody1 = json.dumps(messageBody)
    # print(type(messageBody1),messageBody1)
    data["messageBody"] = str(messageBody1)
    # print("data:", type(data), data)
    #
    # 将数据写入JSON文件
    with open('qualityCallback.json', 'w', encoding='utf-8') as f:
        json.dump(data, f)

    headers = {'Content-Type': 'application/json;charset=UTF-8'}
    url = "http://172.19.97.161:7002/scms-vcr/audit/baiduVideoDetectResult"
    response = requests.post(url, data=json.dumps(data), headers=headers)
    print("质量审核回调请求状态码：", response.status_code)
    print("质量审核回调响应结果：", response.text)



# 质量审核应答接口
@app.route("/v3/job/video_defect_detect", methods=['POST','GET', 'PUT'])
def AutoTypeTwo():
    result = {"jobId": "job-ew24352sdfdadlgw2df5"}
    timestamp = int(time.time())
    date_time = time.strftime('%Y%m%d%H%M%S', time.localtime(timestamp))
    CorrelateID = "AutoTypeTwo_" + date_time
    result["jobId"] = CorrelateID

    req_data = request.data.decode('utf-8')  # 获取请求数据
    data = json.loads(req_data)
    print("质量审核请求data：", data)
    source = data["source"]["url"]

    thread = Thread(target=qualityCallBack, kwargs={"taskId": CorrelateID, "source": source})
    thread.start()

    print("质量审核应答:", result)
    return result

if __name__ == '__main__':
    # app.run()
    # app.run(host='172.19.132.137:6666',debug=True)
    server = pywsgi.WSGIServer(("172.19.133.17", 6666), app)
    server.serve_forever()
    # qualityCallBack('BaiduAuto_20230626163358','http://172.19.97.162:8081//opt/scms/NAS/blues/liyifeng-douyin.mp4')
